package com.chaochis.springboottestdemo.service.impl;

import com.chaochis.springboottestdemo.constant.UserCacheConstant;
import com.chaochis.springboottestdemo.exception.TokenExpiredException;
import com.chaochis.springboottestdemo.model.apiResultVo.ApiUser;
import com.chaochis.springboottestdemo.model.serviceModel.JwtToken;
import com.chaochis.springboottestdemo.model.serviceModel.RedisCacheUser;
import com.chaochis.springboottestdemo.service.CacheRedisUserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service("cacheRedisUserService")
public class CacheRedisUserServiceImpl implements CacheRedisUserService {

  private final RedisTemplate<String, Object> redisTemplate;

  public CacheRedisUserServiceImpl(@Qualifier("redisJackJsonTemplate") RedisTemplate<String, Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  @Override
  public ApiUser getUserInfoByToken(String token) throws Exception {
    var jwtToken = JwtToken.build(token);
    var keyName = String.format(UserCacheConstant.LOGIN_USER, jwtToken.getUserName());
    var cacheUser = this.redisTemplate.opsForValue().get(keyName);
    if (cacheUser == null) {
      throw new TokenExpiredException("token已过期!");
    }
    if (RedisCacheUser.class != cacheUser.getClass()) {
      throw new Exception("从缓存中获取到的用户对象类型错误!");
    }
    return ((RedisCacheUser) cacheUser).getApiUser();
  }
}
